#!/usr/bin/env python
# encoding: utf-8
__author__ = 'Zjay '
"""
@version: 3.6.3
@author: Zjay 
@license: Apache Licence 
@site: 
@software: PyCharm
@file: Grammar_Test_thread.py
@time: 2017/12/10 12:00
"""

# region 单线程

# from time import ctime, sleep
#
#
# def loop0():
#     print('start loop 0 at', ctime())
#     sleep(2)
#     print('start loop 0 at', ctime())
#
#
# def loop1():
#     print('start loop 1 at', ctime())
#     sleep(2)
#     print('start loop 1 at', ctime())
#
#
# def main():
#     print('start mani at', ctime())
#     loop0()
#     loop1()
#     print('all is end at', ctime())
#
#
# if __name__ == '__main__':
#     main()
# endregion

# region 多线程
# import threading
# from time import ctime, sleep
#
# loops = [2, 2]
#
#
# def loop(nloop, nesc):
#     print('start loop', nloop, 'at', ctime())
#     sleep(nesc)
#     print('loop', nloop, 'done at', ctime())
#
#
# def main():
#     print('start at:', ctime())
#     threads = []
#     nloops = range(len(loops))
#     for i in nloops:
#         t = threading.Thread(target=loop, args=(i, loops[i]))
#         threads.append(t)
#
#     for i in nloops:
#         threads[i].start()
#     for i in nloops:
#         threads[i].join()
#     print('all is over:', ctime())

# endregion

# region  练习
# from atexit import register
# from re import compile
# from threading import Thread
# from time import ctime, sleep
# from urllib import request as urlopen
#
# REGEX = compile('#([\d,]+) in Books')
# AMZN = 'http://www.amazon.com/dp/'
# ISBN = {
#     '0132269937': 'core Python programming',
#     '0132356139': 'Python web Development',
#     '0137143419': 'Python Fundamentals'
# }
#
#
# def getRanking(isbn):
#     try:
#         path = '{0}{1}'.format(AMZN, isbn)
#         page = urlopen.urlopen(path)
#         data = page.read()
#         page.close()
#         return REGEX.findall(data)[0]
#     except BaseException as ex:
#         print('error:', ex)
#     finally:
#         return None
#
#
# def _showRanking(isbn):
#     Thread(target=getRanking, args=(isbn,)).start()
#
#     print('_ %r ranked %s ' % (ISBN[isbn], getRanking(isbn)))
#
#
# def main():
#     print('at', ctime(), 'on Amazon...')
#     for isbn in ISBN:
#         _showRanking(isbn)
#
#
# @register
# def _atexit():
#     print('all is done: ', ctime())

# endregion
# region Lock
from atexit import register
from random import randrange
from threading import Thread, Lock, currentThread
from time import ctime, sleep


class CleanoutputSet(set):
    def __str__(self):
        return ','.join(x for x in self)


lock = Lock()
loops = (randrange(2, 5) for x in range(randrange(3, 7)))
remaining = CleanoutputSet()


def loop(nsec):
    try:
        myname = currentThread.__name__
        lock.acquire()
        remaining.add(myname)
        print('{0} Start{1}'.format(ctime(), myname))
        lock.release()
        sleep(nsec)
        lock.acquire()
        remaining.remove(myname)
        print('{0} Completed{1}'.format(ctime(), myname))
        lock.release()
    except BaseException as ex:
        print('Error:',ex)


def main():
    for pause in loops:
        print(pause)
        Thread(target=loop, args=(pause,)).start()


@register
def _atexit():
    print('all is over', ctime())


# endregion

if __name__ == '__main__':
    main()
